package org.linlinjava.litemall.db.service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.linlinjava.litemall.db.beans.Constants;
import org.linlinjava.litemall.db.dao.LitemallOrderGoodsMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.dto.AdminGoodsSalesStatisticsDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import static org.linlinjava.litemall.db.beans.Constants.MESSAGE_TYPE_CHICKEN;

@Service
public class LitemallOrderGoodsService  {
    @Resource
    private LitemallOrderGoodsMapper orderGoodsMapper;

    /**
     * 订单服务
     */
    @Autowired
    private LitemallOrderService orderService;

//    /**
//     * 订单商品服务
//     */
//    @Autowired
//    private LitemallOrderGoodsService orderGoodsService;

    /**
     * litemall商品服务
     */
    @Autowired
    private LitemallMerchandiseService litemallMerchandiseService;

    /**
     * litemall商店商品服务
     */
    @Autowired
    private LitemallShopMerchandiseService litemallShopMerchandiseService;

    /**
     * litemall订单商品服务
     */
    @Autowired
    private LitemallOrderMerchandiseService litemallOrderMerchandiseService;

    /**
     * litemall商品配件服务
     */
    @Autowired
    private LitemallGoodsAccessoryService litemallGoodsAccessoryService;

    /**
     * 产品规范商品服务
     */
    @Autowired
    private LitemallGoodsSpecificationMerchandiseService goodsSpecificationMerchandiseService;

    /**
     * litemall订货配件服务
     */
    @Autowired
    private LitemallOrderGoodsAccessoryService litemallOrderGoodsAccessoryService;


    public int add(LitemallOrderGoods orderGoods) {
        orderGoods.setAddTime(LocalDateTime.now());
        orderGoods.setUpdateTime(LocalDateTime.now());
        return orderGoodsMapper.insertSelective(orderGoods);
    }

    public List<LitemallOrderGoods> getOrderGoodsByIds(List<Integer> ids){
        return orderGoodsMapper.selectBatchIds(ids);
    }



    public Integer getGoodsSales(Integer goodsId, Integer shopId) {
        return orderGoodsMapper.getGoodsSales( goodsId,  shopId);
    }

    public Integer getGoodsPayPersonNum(Integer goodsId, Integer shopId) {
        return orderGoodsMapper.getGoodsPayPersonNum( goodsId,  shopId);
    }

    public List<LitemallOrderGoods> queryByGidAndSid(Integer goodsId, Integer shopId) {
        return orderGoodsMapper.selectList(Wrappers.lambdaQuery(LitemallOrderGoods.class)
                .eq(LitemallOrderGoods::getGoodsId,goodsId)
                .eq(shopId!=null,LitemallOrderGoods::getShopId,shopId));
        /*LitemallOrderGoodsExample example = new LitemallOrderGoodsExample();
        if(shopId != null){
            example.or().andGoodsIdEqualTo(goodsId).andShopIdEqualTo(shopId).andDeletedEqualTo(false);
        }else{
            example.or().andGoodsIdEqualTo(goodsId).andDeletedEqualTo(false);
        }
        return orderGoodsMapper.selectByExample(example);*/
    }

    public List<LitemallOrderGoods> queryByGid(Integer goodsId) {
        return queryByGidAndSid(goodsId, null);
    }

    public List<LitemallOrderGoods> queryByOid(Integer orderId) {
        LitemallOrderGoodsExample example = new LitemallOrderGoodsExample();
        example.or().andOrderIdEqualTo(orderId).andDeletedEqualTo(false);

        example.setOrderByClause("add_time desc");
        return orderGoodsMapper.selectByExample(example);
    }


    public Boolean inserRemark(String remark,Integer orderGoodsId){
        Integer result = orderGoodsMapper.update(null,Wrappers.lambdaUpdate(LitemallOrderGoods.class)
                .eq(LitemallOrderGoods::getOrderId, orderGoodsId)
                .set(LitemallOrderGoods::getRemark, remark)
        );
        return result>0;
    }

    public List<LitemallOrderGoods> queryByOidNotRefund(Integer orderId) {
        LitemallOrderGoodsExample example = new LitemallOrderGoodsExample();
        example.or().andOrderIdEqualTo(orderId).andDeletedEqualTo(false);

        example.setOrderByClause("add_time desc");
        return orderGoodsMapper.selectByExample(example);
    }

    public List<LitemallOrderGoods> findByOidAndGid(Integer orderId, Integer goodsId) {
        LitemallOrderGoodsExample example = new LitemallOrderGoodsExample();
        example.or().andOrderIdEqualTo(orderId).andGoodsIdEqualTo(goodsId).andDeletedEqualTo(false);
        return orderGoodsMapper.selectByExample(example);
    }

    public List<LitemallOrderGoods> findByShopIdAndGoodsid(Integer shopId, Integer goodsId) {
        LitemallOrderGoodsExample example = new LitemallOrderGoodsExample();
        example.or().andShopIdEqualTo(shopId).andGoodsIdEqualTo(goodsId).andDeletedEqualTo(false);
        return orderGoodsMapper.selectByExample(example);
    }

    public LitemallOrderGoods findById(Integer id) {
        return orderGoodsMapper.selectByPrimaryKey(id);
    }

    public void updateById(LitemallOrderGoods orderGoods) {
        orderGoods.setUpdateTime(LocalDateTime.now());
        orderGoodsMapper.updateByPrimaryKeySelective(orderGoods);
    }

    public Short getComments(Integer orderId) {
        LitemallOrderGoodsExample example = new LitemallOrderGoodsExample();
        example.or().andOrderIdEqualTo(orderId).andDeletedEqualTo(false);
        long count = orderGoodsMapper.countByExample(example);
        return (short) count;
    }

    public boolean checkExist(Integer goodsId) {
        LitemallOrderGoodsExample example = new LitemallOrderGoodsExample();
        example.or().andGoodsIdEqualTo(goodsId).andDeletedEqualTo(false);
        return orderGoodsMapper.countByExample(example) != 0;
    }

    public List<LitemallOrderGoods> queryGoodsStatistics(LocalDateTime startTime, LocalDateTime endTime, Integer shopId, Integer goodsId) {
        LitemallOrderGoodsExample example = new LitemallOrderGoodsExample();
        LitemallOrderGoodsExample.Criteria criteria = example.or();
        if(!ObjectUtils.isEmpty(shopId)){
            criteria.andShopIdEqualTo(shopId);
        }
        if(!ObjectUtils.isEmpty(goodsId)){
            criteria.andGoodsIdEqualTo(goodsId);
        }
        if (!ObjectUtils.isEmpty(startTime) && !ObjectUtils.isEmpty(endTime)) {
            criteria.andUpdateTimeBetween(startTime, endTime);
        }

        criteria.andDeletedEqualTo(false);
        return orderGoodsMapper.selectByExample(example);
    }

    public List<LitemallOrderGoods> queryGoodsSalesStatistics(Integer goodsId, Integer categoryId, LocalDateTime startTime,  LocalDateTime endTime, Integer page,
                                                         Integer limit, String sort, String order) {
        LitemallOrderGoodsExample example = new LitemallOrderGoodsExample();
        LitemallOrderGoodsExample.Criteria criteria = example.or();
        if(!ObjectUtils.isEmpty(goodsId)){
            criteria.andGoodsIdEqualTo(goodsId);
        }
        if(!ObjectUtils.isEmpty(categoryId)){
            criteria.andCategoryIdEqualTo(categoryId);
        }
        if (!ObjectUtils.isEmpty(startTime) && !ObjectUtils.isEmpty(endTime)) {
            criteria.andAddTimeBetween(startTime, endTime);
        }
        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }
//        PageHelper.startPage(page, limit);
        criteria.andDeletedEqualTo(false);
        return orderGoodsMapper.selectByExample(example);
    }

    public int deleteByOrderId(Integer orderId) {
        LitemallOrderGoodsExample example = new LitemallOrderGoodsExample();
        example.or().andOrderIdEqualTo(orderId).andDeletedEqualTo(false);
        return orderGoodsMapper.deleteByExample(example);
    }

    public int logicDeleteByOrderId(Integer orderId){
        LitemallOrderGoodsExample example = new LitemallOrderGoodsExample();
        example.or().andOrderIdEqualTo(orderId).andDeletedEqualTo(false);
        return orderGoodsMapper.logicalDeleteByExample(example);
    }

    public int deleteById(Integer id) {
    	return orderGoodsMapper.deleteByPrimaryKey(id);
    }

    public List<LitemallOrderGoods> findByOrderIdAndGoodsidAndSpecIds(Integer orderId, Integer goodsId, Integer[] specIds) {
        LitemallOrderGoodsExample example = new LitemallOrderGoodsExample();
        LitemallOrderGoodsExample.Criteria criteria = example.or();
        if(!ObjectUtils.isEmpty(goodsId)){
            criteria.andGoodsIdEqualTo(goodsId);
        }

        if(!ObjectUtils.isEmpty(orderId)){
        	criteria.andOrderIdEqualTo(orderId);
        }

        if(!ObjectUtils.isEmpty(specIds)){
        	criteria.andSpecificationIdsEqualTo(specIds);
        }

        criteria.andDeletedEqualTo(false);
        return orderGoodsMapper.selectByExample(example);
    }

    public boolean checkSpecIdExist(Integer[] specIds) {
        LitemallOrderGoodsExample example = new LitemallOrderGoodsExample();
        example.or().andSpecificationIdsEqualTo(specIds).andDeletedEqualTo(false);
        return orderGoodsMapper.countByExample(example) != 0;
    }

    public int countByOrderIdAndMadeStatus(Integer orderId, Byte madeStatus) {
    	 LitemallOrderGoodsExample example = new LitemallOrderGoodsExample();
         LitemallOrderGoodsExample.Criteria criteria = example.or();

         if(!ObjectUtils.isEmpty(orderId)){
         	criteria.andOrderIdEqualTo(orderId);
         }

         if(!ObjectUtils.isEmpty(madeStatus)){
         	criteria.andMadeStatusEqualTo(madeStatus);
         }

         criteria.andDeletedEqualTo(false);
         return (int)orderGoodsMapper.countByExample(example);
    }

    public List<LitemallOrderGoods> queryByOrderIdAndOrderGoodsId(Integer orderId,List<Integer> orderGoodsIds){
        LitemallOrderGoodsExample example = new LitemallOrderGoodsExample();
        LitemallOrderGoodsExample.Criteria criteria = example.or();
        criteria.andOrderIdEqualTo(orderId);
        criteria.andIdNotIn(orderGoodsIds);

        return orderGoodsMapper.selectByExample(example);
    }

    public Integer orderGoodsNum(List<Integer> orderIds) {
        return orderGoodsMapper.selectList(Wrappers.lambdaQuery(LitemallOrderGoods.class).in(LitemallOrderGoods::getOrderId,orderIds)).size();
    }

    public Integer PayOrderGoodsNum(List<Integer> payOrderGoodsNumOrderIds) {
        return orderGoodsMapper.selectList(Wrappers.lambdaQuery(LitemallOrderGoods.class).in(LitemallOrderGoods::getOrderId,payOrderGoodsNumOrderIds)).size();
    }

    public List<LitemallOrderGoods> groupByGoods(Integer shopId, LocalDateTime startTimes, LocalDateTime endTimes) {
        return orderGoodsMapper.selectList(Wrappers.lambdaQuery(LitemallOrderGoods.class).groupBy(LitemallOrderGoods::getGoodsId));
    }

    public IPage<LitemallOrderGoods> groupByGoods(Integer shopId,Integer limit, Integer page, Long categoryl3, Integer goodsId, List<Integer> goodsIds) {
        //PageHelper.startPage(page, limit-1);
        return orderGoodsMapper.selectPage(new Page<>(page,limit),Wrappers.lambdaQuery(LitemallOrderGoods.class)
                        .eq(shopId!=null,LitemallOrderGoods::getShopId,shopId)
                        .eq(categoryl3!=null,LitemallOrderGoods::getCategoryId,categoryl3)
                        .eq(goodsId!=null,LitemallOrderGoods::getGoodsId,goodsId)
                        .in(CollUtil.isNotEmpty(goodsIds),LitemallOrderGoods::getGoodsId,goodsIds)
                .groupBy(LitemallOrderGoods::getGoodsId));
    }

    public AdminGoodsSalesStatisticsDTO goodsSalesStatistics(Integer goodsId,Integer shopId,LocalDateTime startTimes,LocalDateTime endTimes) {
        return orderGoodsMapper.goodsSalesStatistics(goodsId, shopId, startTimes, endTimes);
    }

    public List<LitemallOrderGoods> selectList(Integer goodsId, Integer shopId, LocalDateTime startTimes, LocalDateTime endTimes) {
        LambdaQueryWrapper<LitemallOrderGoods> eq = Wrappers.lambdaQuery(LitemallOrderGoods.class)
                .eq(goodsId!=null,LitemallOrderGoods::getGoodsId, goodsId)
                .eq(shopId!=null,LitemallOrderGoods::getShopId, shopId)
                .between(startTimes != null, LitemallOrderGoods::getAddTime, startTimes, endTimes);
        return orderGoodsMapper.selectList(eq);
    }

    public List<LitemallOrderGoods> selectList(LambdaQueryWrapper<LitemallOrderGoods> goodsQueryWrapper) {
        return orderGoodsMapper.selectList(goodsQueryWrapper);
    }

    /**
     * 将制作完成的订单改为自动改成已完成
     * @param orderStatus
     * @param shopId
     */
    public void makeOrderStateFinish(Short orderStatus,Integer shopId){
        //查询单个门店当天待收货订单
        List<LitemallOrder> orderList = orderService.shopWaitDeliveryOrder(orderStatus, shopId);
        orderList.forEach(order -> {
            //通过订单获取所有订单商品
            List<LitemallOrderGoods> orderGoodsList = queryByOid(order.getId());
            //判断订单商品中的商品是否全部已经完成了
            boolean allSameValue = orderGoodsList.stream()
                    .allMatch(orderGoods -> orderGoods.getMadeStatus() != null && 2 == orderGoods.getMadeStatus());
            if(allSameValue){
                //将订单表的状态改为已完成订单
                updateMadeStatus(order.getId(), Constants.ORDER_MADE_STATUS_PICKUP);
            }
        });

    }

    /**
     * 更新了状态
     * 更新制作状态
     *
     * @param orderId    订单id
     * @param madeStatus 状态
     */
    @Transactional
    public void updateMadeStatus(Integer orderId, Byte madeStatus) {
        LitemallOrder litemallOrder = orderService.findById(orderId);
        //如果为已取餐，则修改订单状态为已取餐
        if (Constants.ORDER_MADE_STATUS_PICKUP.equals(madeStatus)) {
            litemallOrder.setOrderStatus(Constants.ORDER_STATUS_PICKUP);
            //TODO 原料的扣减
            List<LitemallOrderGoods> orderGoodsList = queryByOid(orderId);
            if (!CollectionUtils.isEmpty(orderGoodsList)) {
                for (LitemallOrderGoods litemallOrderGoods : orderGoodsList) {
                    Map<Integer, BigDecimal> merMap = caculateMerchandise(litemallOrderGoods, true);
                    for (Integer merchandiseId : merMap.keySet()) {
                        BigDecimal consumerNumber = merMap.get(merchandiseId).multiply(new BigDecimal(litemallOrderGoods.getNumber()));

                        //新增原料损耗记录
                        LitemallOrderMerchandise orderMerchandise = new LitemallOrderMerchandise();
                        orderMerchandise.setOrderId(orderId);
                        Integer shopId = litemallOrderGoods.getShopId();
                        orderMerchandise.setShopId(shopId);
                        orderMerchandise.setOrderGoodsId(litemallOrderGoods.getId());
                        orderMerchandise.setGoodsId(litemallOrderGoods.getGoodsId());
                        orderMerchandise.setGoodsName(litemallOrderGoods.getGoodsName());
                        orderMerchandise.setGoodsSn(litemallOrderGoods.getGoodsSn());
                        orderMerchandise.setMerchandiseId(merchandiseId);
                        LitemallMerchandise litemallMerchandise = litemallMerchandiseService.findById(merchandiseId);
                        orderMerchandise.setMerchandiseName(litemallMerchandise.getName());
                        orderMerchandise.setMerchandiseSn(litemallMerchandise.getMerchandiseSn());
                        orderMerchandise.setConsumerNumber(consumerNumber);
                        litemallOrderMerchandiseService.add(orderMerchandise);
                        //扣减原料
                        LitemallShopMerchandise litemallShopMerchandise = litemallShopMerchandiseService.queryByMerIdAndShopId(merchandiseId, shopId);
                        //计算基本单位的剩余原料
                        Double basicRemainNumber = new BigDecimal(litemallShopMerchandise.getBasicNumber()).subtract(consumerNumber).setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue();
                        litemallShopMerchandise.setBasicNumber(basicRemainNumber);
                        //计算盘点单位的剩余原料
                        Double checkRemainNumber = basicRemainNumber / litemallMerchandise.getCheckRatio();
                        litemallShopMerchandise.setNumber(checkRemainNumber);
                        litemallShopMerchandiseService.updateById(litemallShopMerchandise);
                    }

                }
            }
        }

        //修改订单状态为待支付
        litemallOrder.setMadeStatus(madeStatus);
        orderService.updateById(litemallOrder);
    }

    /**
     * 贵司货物
     * 计算订单商品的原料损耗
     *
     * @param isConsumeRatio     是否计算原料损耗系数
     * @param litemallOrderGoods litemall订货
     * @return 原料损耗map <原料id，损耗的数量>
     */
    private Map<Integer, BigDecimal> caculateMerchandise(LitemallOrderGoods litemallOrderGoods, boolean isConsumeRatio) {
        //创建原料损耗map <原料id，损耗的数量>
        Map<Integer, BigDecimal> merMap = new HashMap<>();
        //计算规格原料
        Integer specId = litemallOrderGoods.getSpecificationIds()[0];
        List<LitemallGoodsSpecificationMerchandise> goodsSpecMerchandises = goodsSpecificationMerchandiseService.queryBySpecid(specId);
        for (LitemallGoodsSpecificationMerchandise goodsSpecMerchandise : goodsSpecMerchandises) {
            Integer merchandiseId = goodsSpecMerchandise.getMerchandiseId();
            BigDecimal number = new BigDecimal(goodsSpecMerchandise.getNumber());
            if (isConsumeRatio) {//计算消耗系数
                number = number.multiply(goodsSpecMerchandise.getConsumeRatio());
            }
            BigDecimal merNumber = merMap.get(merchandiseId);
            if (null == merNumber) {
                merMap.put(merchandiseId, number);
            } else {
                merMap.put(merchandiseId, merNumber.add(merNumber));
            }
        }
        //计算辅料原料
        List<LitemallOrderGoodsAccessory> orderGoodsAccessorys = litemallOrderGoodsAccessoryService.findByOrderGoodsId(litemallOrderGoods.getId());
        for (LitemallOrderGoodsAccessory orderGoodsAccessory : orderGoodsAccessorys) {
            Integer accessoryId = orderGoodsAccessory.getAccessoryId();
            LitemallGoodsAccessory accessory = litemallGoodsAccessoryService.findById(accessoryId);

            Integer merchandiseId = accessory.getMerchandiseId();
            //计算辅料原料的损耗量 = 份数 * 每份辅料原料的数量  * 损耗系数
            BigDecimal number = new BigDecimal(orderGoodsAccessory.getNumber() * accessory.getNumber());
            if (isConsumeRatio) {//计算消耗系数
                number = number.multiply(accessory.getConsumeRatio());
            }
            BigDecimal merNumber = merMap.get(merchandiseId);
            if (null == merNumber) {
                merMap.put(merchandiseId, number);
            } else {
                merMap.put(merchandiseId, merNumber.add(merNumber));
            }
        }
        return merMap;
    }

    /**
     * 修改订单制作状态
     */
    public void modifyOrderMakeState(Short orderStatus,Integer shopId){
        //查询单个门店当天待收货以及待制作订单
        List<LitemallOrder> orderList = orderService.shopWaitDeliveryOrder(orderStatus, shopId);
        orderList.forEach(order -> {
            //通过订单id去查订单商品
            List<LitemallOrderGoods> orderGoodsList = queryByOid(order.getId());
            for (int i = 0; i < orderGoodsList.size(); i++) {
                updateMadeStatus(orderGoodsList.get(i).getId(),Constants.ORDER_GOODS_MADE_STATUS_FINISHED,order.getUserId(),orderGoodsList.get(i).getRemark().get(i).getIndex());
            }
//            boolean isMake = orderGoodsList.stream().allMatch(orderGoods -> Constants.ORDER_MADE_STATUS_PICKUP.equals(orderGoods.getMadeStatus()));
//            //如果全都是已制作完成的商品，那就将订单的制作状态改为制作完成
//            if(isMake){
//                order.setMadeStatus(Constants.ORDER_MADE_STATUS_PICKUP);
//                orderService.updateById(order);
//            }
        });

    }

    /**
     * 修改制作状态
     * @param orderGoodsId
     * @param madeStatus
     */
    @Transactional
    public void updateMadeStatus(Integer orderGoodsId, Byte madeStatus,Integer userId,Integer index) {
        String orderSn="";
        Lock lock = new ReentrantLock();
        try {
            lock.lock();
            LitemallOrderGoods orderGoods = findById(orderGoodsId);
            if (null == orderGoods) {
                return;
            }
            Integer orderId = orderGoods.getOrderId();
            LitemallOrder litemallOrder = orderService.findById(orderId);
            orderSn=litemallOrder.getOrderSn();
            if (!Constants.ORDER_STATUS_ONGOING.equals(litemallOrder.getOrderStatus()) ) {
                //进行中制作中的订单才能进行操作
                return;
            }
            orderGoods.setMadeUserId(userId);

            if(Constants.ORDER_GOODS_MADE_STATUS_NEW.equals(madeStatus)){
                orderGoods.setMadeUserId(null);
            }


            orderGoods.getRemark().get(index).setIndexMakeStatus(madeStatus.intValue());
            //如果是制作中
            if(Constants.ORDER_GOODS_MADE_STATUS_ONGOING==madeStatus){
                //修改订单商品的制作状态
                orderGoods.setMadeStatus(madeStatus);
            }
            //如果是已完成
            if(Constants.ORDER_GOODS_MADE_STATUS_FINISHED==madeStatus){
                //修改订单商品的制作状态
                //查看下标制作状态是否全部制作才算制作完成

                long count = orderGoods.getRemark().stream().filter(indexMake -> indexMake.getIndexMakeStatus() != 2).count();
                orderGoods.setMadeStatus(count==0?madeStatus:Constants.ORDER_GOODS_MADE_STATUS_ONGOING);
            }
            //如果是取消制作
            if(Constants.ORDER_GOODS_MADE_STATUS_NEW==madeStatus){
                //修改订单商品的制作状态
                //查看下标制作状态是否全部制作才算制作完成
                long count = orderGoods.getRemark().stream().filter(indexMake -> indexMake.getIndexMakeStatus() == 0).count();
                orderGoods.setMadeStatus(count==orderGoods.getNumber()?madeStatus:Constants.ORDER_GOODS_MADE_STATUS_ONGOING);
            }

            updateById(orderGoods);

            //如果为制作完成，则需要判断是否该订单的所有商品都已制作完成
            if (Constants.ORDER_GOODS_MADE_STATUS_FINISHED.equals(madeStatus)) {
                //订单量
                int total = countByOrderIdAndMadeStatus(orderId, null);
                //制作完成量
                int finish = countByOrderIdAndMadeStatus(orderId, Constants.ORDER_GOODS_MADE_STATUS_FINISHED);
                if (total == finish) {
                    LitemallOrder order = new LitemallOrder();
                    order.setId(orderId);
                    order.setMadeStatus(Constants.ORDER_MADE_STATUS_PICKUP);
                    orderService.updateById2(order);
                }
            }

            //如果订单中有一个商品在制作，则将订单改成制作中
            //拿到订单中所有的商品订单
            List<LitemallOrderGoods> orderGoodsList = queryByOid(orderId);
            litemallOrder.setMadeStatus((byte)0);
            orderService.updateById2(litemallOrder);
            for(LitemallOrderGoods orderGoods1:orderGoodsList){
                if(orderGoods1.getMadeStatus().intValue()==1||orderGoods1.getMadeStatus().intValue()==2){
                    litemallOrder.setMadeStatus((byte)1);
                    orderService.updateById2(litemallOrder);
                }
            }
            //如果所有 完成商品订单数等于所有商品数，则将订单状态改成已完成
            if(orderGoodsList.size()==orderGoodsList.stream().filter( maStatus -> maStatus.getMadeStatus()==2).collect(Collectors.toList()).size()){
                litemallOrder.setMadeStatus((byte)2);
                orderService.updateById2(litemallOrder);
            }
        }catch (Exception e){
            //手动强制回滚事务，这里一定要第一时间处理
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }finally {
            lock.unlock();
        }
    }


}
